# -*- coding: utf-8 -*- 
from flask import Blueprint, jsonify, request
from dante.database import db_session, Sms
from dante.util import Result
from dante import core
import datetime
import yunpian
import logging, json

mod = Blueprint('general', __name__)
logger = logging.getLogger('Dante')

@mod.route('/send-sms', methods=['GET', 'POST'])
def send_sms():
  args = request.args if request.method == 'GET' else request.form
  mobile = args.get('phone')
  content = args.get('content')
  time_data = args.get('schedule_time', datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
  schedule_time = datetime.datetime.strptime(time_data,'%Y-%m-%d %H:%M:%S')
  source_ip = request.headers.get('X-Real-Ip', request.remote_addr)
  logger.info('Get request of sending message to mobile {0}, content {1}, schedule_time {2} from {3}'.format(mobile, content, schedule_time, source_ip))
  sms = Sms(mobile, content, schedule_time, source_ip)
  db_session.add(sms)
  db_session.commit()

  core.arrange_job(sms.id, schedule_time)

  return json.dumps(Result().success().set_message('Request success').to_dict())
